package Thread.ThreadPoll;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
//自己实现一个非常简单的线程池

class MyThreadPool{
    //传入参数 n，表示 要创建多少线程，并调用构造方法创建
    public BlockingQueue<Runnable> queue=new ArrayBlockingQueue<>(1000);
    public MyThreadPool(int n){
        for (int i = 0; i < n; i++) {
            Thread t=new Thread(()->{
                while(true){
                    Runnable runnable= null;
                    try {
                        runnable = queue.take();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    runnable.run();
                }
            });
            t.start();
        }
    }

    //添加任务
    public void submit(Runnable task){
        try {
            queue.put(task);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}

public class Demo37 {

    public static void main(String[] args) {
        // 创建一个包含4个线程的线程池
        MyThreadPool pool=new MyThreadPool(4);
        // 循环提交1000个任务到线程池中
        for (int i = 0; i < 1000; i++) {
            // 捕获当前循环变量的值，用于在lambda表达式中使用
            int id=i;
            pool.submit(()->{
                System.out.println("任务"+id+","+Thread.currentThread().getName());
            });
        }
    }
}
